package c_processPkg

import (
	"Infinichat_mixed/entity"
	"Infinichat_mixed/transfer"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"net"
)

type UserProcess struct{}

var CurConn net.Conn

func (this *UserProcess) Login(userAcccount string, userPwd string) (err error) {
	// TODO 测试用
	userPwd = "123456"
	CurConn, err = net.Dial("tcp", "localhost:8889")
	if err != nil {
		fmt.Println("Dial err:", err)
		return
	}
	defer CurConn.Close()
	var mes *entity.Message = new(entity.Message)
	mes.Type = entity.LoginMesType
	var loginMes entity.LoginMes
	loginMes.UserAccount = userAcccount
	loginMes.UserPwd = userPwd
	//loginMes.UserName = "scott"
	data, err := json.Marshal(loginMes)
	if err != nil {
		fmt.Println("Marshal err:", err)
		return
	}
	mes.Data = string(data)
	data, err = json.Marshal(mes)
	if err != nil {
		fmt.Println("Marshal err:", err)
		return
	}
	var pkgLen uint32
	pkgLen = uint32(len(data))
	var buf [4]byte
	binary.BigEndian.PutUint32(buf[0:4], pkgLen)
	// 发送消息长度
	n, err := CurConn.Write(buf[:4])
	if n != 4 || err != nil {
		return
	}
	//fmt.Println("send msg len:", pkgLen)
	//fmt.Println("content:", string(data))

	// 发送消息本身
	_, err = CurConn.Write(data)
	if err != nil {
		fmt.Println("Write err:", err)
	}

	//time.Sleep(5 * time.Second)
	//fmt.Println("Sleep 20...")
	tf := transfer.Transfer{
		Conn: CurConn,
	}
	mes, err = tf.ReadPkg()
	//fmt.Println("mes:", mes)
	if err != nil {
		fmt.Println("Read err:", err)
	}
	var loginResMes entity.LoginResMes
	err = json.Unmarshal([]byte(mes.Data), &loginResMes)
	//fmt.Println("enter:", loginResMes)
	if loginResMes.Code == 200 {
		CurUser.Conn = CurConn
		CurUser.User = loginResMes.User
		fmt.Printf("login success! user:{account:%s,name:%s}\n", CurUser.Account, loginResMes.User.Nickname)
		fmt.Print("online user:")
		for _, v := range loginResMes.UserIds {
			fmt.Printf("id:%d \t", v)
			if v == loginResMes.User.ID {
				continue
			}
			// 完成客户端OnlineUsers的初始化
			user := &entity.User{}
			user.ID = v
			user.UserStatus = entity.UserOnline
			OnlineUsers[v] = user
		}
		fmt.Println()
		p2p_msg := loginResMes.P2p_msg
		fmt.Println("p2p_msg:", p2p_msg)
		// 标记为已读
		//p2pMids := []uint{}
		//for _, pmsg := range p2p_msg {
		//	p2pMids = append(p2pMids, pmsg.ID)
		//}
		var p2pMessageRead entity.Message
		p2pMessageRead.Type = entity.NoteP2PReadType
		p2pData, _ := json.Marshal(p2p_msg)
		p2pMessageRead.Data = string(p2pData)
		p2pReadData, _ := json.Marshal(p2pMessageRead)
		_ = tf.WriterPkg(p2pReadData)
		p2m_msg := loginResMes.P2m_msg
		fmt.Println("p2m_msg:", p2m_msg)
		ids := loginResMes.AddIds
		fmt.Println("request addIds:", ids)
		gis := loginResMes.Gis
		fmt.Println("request groupInvite:", gis)
		go serverProcessMes(CurConn)
		go startSender(CurConn)
		ShowMenu()
	} else {
		fmt.Println(loginResMes.Error)
	}
	return
}

type SO struct {
	target_id uint
	content   string
}

// 管道发送私聊消息
var SendChan = make(chan *SO, 100)

func startSender(Conn net.Conn) {
	go func() {
		for so := range SendChan {
			_ = S2O(Conn, so.target_id, so.content)
		}
	}()
}
